package com.zero.zsingleton
{
	import com.open.utils.StringUtils;
	
	import flash.utils.Dictionary;

	public class LanguageSingleton
	{
		private static var _instance:LanguageSingleton;		
		
		private var nAllExp		:RegExp = /\\n/g;
		private var _reg			:RegExp = new RegExp("\\{(\\d+)\\}");
		public var onCompleteCall	:Function;
		private var _languages		:Dictionary;
		
		public var message					:String;
		public var analyzeCompleteCall		:Function;
		public var analyzeErrorCall		:Function;
		
		public function LanguageSingleton()
		{
			_languages = new Dictionary();
		}
		
		public static function get instance():LanguageSingleton
		{
			if(!_instance)
			{
				_instance = new LanguageSingleton();
			}
			return _instance;
		}
		
		public function analyze(data:*):void
		{
			var list:Array = String(data).split("\n");
			for(var i:int = 0; i < list.length; i ++)
			{
				var s:String = list[i];
				if(s.indexOf("#") == 0)
					continue;
				s = s.replace("\\r","\r");
				s = s.replace(nAllExp,"\n");
				var index:int = s.indexOf(":");
				if(index != -1)
				{
					var name:String = s.substring(0,index);
					var value:String = s.substr(index + 1);
					value = value.split("##")[0];
					_languages[name] = StringUtils.trimRight(value);
				}
			}
			onAnalyzeComplete();
		}
		
		private function onAnalyzeComplete():void
		{
			if(onCompleteCall != null)onCompleteCall(this);
			if(analyzeCompleteCall != null)analyzeCompleteCall();
		}
		
		private function onAnalyzeError():void
		{
			if(analyzeErrorCall != null)analyzeErrorCall();
		}
		
		public function GetTranslation(translationId:String,...args):String
		{
			var input:String = _languages[translationId]  ? _languages[translationId] : "";
			var obj:Object = _reg.exec(input);
			while(obj && args.length > 0)
			{
				var id:int = int(obj[1]);
				if(id >= 0 && id < args.length)
				{
					input =input.replace(_reg,args[id]);
				}
				else
				{
					input = input.replace(_reg,"{}");
				}
				obj = _reg.exec(input);
			}
			return input;
		}
	}
}